/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lcfgly.Form.Validation;

import com.lcfgly.CustomBean.SimpleUserInferForm;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * 简易用户信息修改验证
 * @author lcfgly
 */
public class SimpleUserInferValidation implements Validator{

    @Override
    public boolean supports(Class<?> clazz) {
        return SimpleUserInferForm.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        SimpleUserInferForm form=(SimpleUserInferForm)target;
        try {
            String phone="[0-9\\(\\-\\)]*";
            Pattern pregex=Pattern.compile(phone);
            if(!form.getEmail().isEmpty()){
                String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
                Pattern regex = Pattern.compile(check);
                Matcher matcher = regex.matcher(form.getEmail());
                if (!matcher.matches())
                    errors.rejectValue("email", null, "电子邮箱格式有误!请填写正确的邮箱");
            }
            if(!form.getPhone().isEmpty()){
                Matcher matcher1=pregex.matcher(form.getPhone());
                if (!matcher1.matches()) {
                    errors.rejectValue("phone", null, "电话号码出现非法字符请检查!");
                }else if(form.getPhone().length()>15){
                    errors.rejectValue("phone", null, "电话号码过长请检查是否正确!");
                }
            }
            if(!form.getTel().isEmpty()){
                Matcher matcher2=pregex.matcher(form.getTel());
                if(!matcher2.matches()){
                    errors.rejectValue("tel", null, "传真号码出现非法字符请检查!");
                }
            }
        } catch (Exception e) {
            errors.rejectValue("fax", null, "错误请检查输入的数据内容!");
        }
    }
    
}
